package com.china08.yxyapi.api.manage.tec.teaching.homework.worklist.workinfo.report;

import java.text.ParseException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageImpl;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort.Direction;
import org.springframework.http.MediaType;
import org.springframework.util.Assert;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import com.china08.yxyapi.api.YxyApiBaseController;
import com.china08.yxyapi.entity.mg.homework.HomeworkTask;
import com.china08.yxyapi.entity.mg.homework.HomeworkTaskReport;
import com.china08.yxyapi.entity.mg.homework.HomeworkTaskReportQues;
import com.china08.yxyapi.model.YxyApiPageReqModel;
import com.china08.yxyapi.model.YxyApiRespModel;
import com.china08.yxyapi.repository.mg.homework.HomeworkTaskQuesRepository;
import com.china08.yxyapi.repository.mg.homework.HomeworkTaskReportQuesRepository;
import com.china08.yxyapi.repository.mg.homework.HomeworkTaskReportRepository;
import com.china08.yxyapi.repository.mg.homework.HomeworkTaskRepository;

/**
 * 查询详情-成绩单
 */
@CrossOrigin
@RestController
public class HomeworkReportController extends YxyApiBaseController {

    @Autowired
    HomeworkTaskReportRepository homeworkTaskReportRepository;

    @Autowired
    HomeworkTaskReportQuesRepository homeworkTaskReportQuesRepository;

    @Autowired
    HomeworkTaskQuesRepository homeworkTaskQuesRepository;

    @Autowired
    private HomeworkTaskRepository homeworkTaskRepository;

    @ResponseBody
    @RequestMapping(value = "/api_yw/manage/tec/teaching/homework/worklist/workinfo/report/find", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    public Page<RespModel> precess(//
            HttpServletRequest request, //
            HttpServletResponse response, //
            @RequestBody ReqModel reqModel, //
            RespModel respModel) throws ParseException {
        // ##
        // 获取用户基本信息
        try {
            reqModel.userId = getProfile(request, response).getId();
            reqModel.schoolId = getProfile(request, response).getSchoolId();
        } catch (Exception e) {
            Assert.isTrue(false, "用户信息异常，请重新登录。");
        }
        // return
        Pageable pageable = new PageRequest(reqModel.page, reqModel.size, Direction.DESC, "scoreRate");
        List<RespModel> respModelLst = new ArrayList<RespModel>();
        // 获取学生作业情况
        Page<HomeworkTaskReport> homeworkTaskReports = homeworkTaskReportRepository
                .findByTaskIdAndClassIdOrderByScoreRateDescDurationAsc(reqModel.taskId, reqModel.classId, pageable);
        // 获取学生通知类作业详情
        List<String> studentIds = new ArrayList<String>();
        homeworkTaskReports.getContent().forEach(homeworkTaskReport -> {
            studentIds.add(homeworkTaskReport.getStudentId());
        });
        List<HomeworkTaskReportQues> homeworkTaskReportQues = homeworkTaskReportQuesRepository
                .findByStudentIdInAndTaskIdAndQuestionType(studentIds, reqModel.taskId, "2");
        Integer count = homeworkTaskQuesRepository.countByTaskIdAndQuesType(reqModel.taskId, "2");
        Map<String, String> studentQues = new HashMap<String, String>();
        homeworkTaskReportQues.forEach(workTaskReportQues -> {
            studentQues.put(workTaskReportQues.getStudentId(),
                    this.getNotifyPassed(workTaskReportQues.getNotifyPassed()));
        });
        // 试题总数获取
        Integer quesTotal = homeworkTaskQuesRepository.countByTaskId(reqModel.taskId);
        // 是否有通知类试题
        Integer count1 = homeworkTaskQuesRepository.countByTaskIdAndQuesType(reqModel.taskId, "2");
        boolean isNotify = (count1 == null ? false : (count1 > 0 ? true : false));
        // 通知类作业是否需要学生在线提交true需要,false不需要
        HomeworkTask homeworkTask = homeworkTaskRepository.findOne(reqModel.taskId);
        boolean ifNeedSumbit = (homeworkTask == null ? true
                : homeworkTask.getIfNeedSumbit() == null ? true : homeworkTask.getIfNeedSumbit());
        // 数据组装
        homeworkTaskReports.getContent().forEach(homeworkTaskReport -> {
            RespModel model = new RespModel();
            model.taskId = homeworkTaskReport.getTaskId();
            model.classId = homeworkTaskReport.getClassId();
            model.studentId = homeworkTaskReport.getStudentId();
            model.studentNick = homeworkTaskReport.getStudentNick();
            model.rightRate = this.rightRate(homeworkTaskReport.getRightRate());
            model.scoreRate = this.rightRate(homeworkTaskReport.getScoreRate());
            model.finishTime = this.getDuration(homeworkTaskReport.getDuration());
            String noticeScore = studentQues.get(homeworkTaskReport.getStudentId());
            model.noticeScore = noticeScore == null ? ((count == null || count == 0) ? "------" : "暂无") : noticeScore;
            model.quesTotal = quesTotal == null ? 0 : quesTotal;
            model.ifNeedSumbit = ifNeedSumbit;
            model.isNotify = isNotify;
            respModelLst.add(model);
        });
        Page<RespModel> respModelPage = new PageImpl<RespModel>(respModelLst, pageable,
                homeworkTaskReports != null ? homeworkTaskReports.getTotalElements() : 0);
        return respModelPage;
    }

    /** 请求参数 **/
    public static class ReqModel extends YxyApiPageReqModel {
        // 任务Id
        public String taskId;
        // 班级Id
        public String classId;
        // 用户Id (不用传参)
        public String userId;
        // 学校Id (不用传参)
        public String schoolId;
    }

    /** 响应 **/
    public static class RespModel extends YxyApiRespModel {
        // 任务Id
        public String taskId;
        // 班级Id
        public String classId;
        // studentId
        public String studentId;
        // studentNick
        public String studentNick;
        // 正确率
        public String rightRate;
        // 得分率
        public String scoreRate;
        // 完成时间
        public String finishTime;
        // 通知作业评分
        public String noticeScore;
        // 是否有通知类试题
        public boolean isNotify = false;
        // 通知类作业是否需要学生在线提交true需要,false不需要
        public boolean ifNeedSumbit = true;
        // 本次作业试题总数
        public int quesTotal = 0;
    }

    // 通知作业评分
    private String getNotifyPassed(Integer notifyPassed) {
        // 通知类作业是否正确 1-A, 2-B, 3-C, 4-D
        if (notifyPassed == null) {
            return "暂无";
        } else {
            // if (notifyPassed == 1) {
            // return "A";
            // } else if (notifyPassed == 2) {
            // return "B";
            // } else if (notifyPassed == 3) {
            // return "C";
            // } else if (notifyPassed == 4) {
            // return "D";
            // } else {
            // return "暂无";
            // }
            return notifyPassed + "分";
        }
    }

    // 时间转化
    private String getDuration(Long duration) {
        if (duration == null || duration == null) { return ""; }
        long time = duration;
        long miao = time % 60; // 秒
        time = time / 60; // 转化为 分
        long shi = time / 60; // 抓换为 时
        long fen = time % 60; // 抓换为 分
        return shi + "时" + fen + "分" + miao + "秒";
    }

    private Double getDouble(Double x1) {
        if (x1 == null) { return 0d; }
        java.text.DecimalFormat df = new java.text.DecimalFormat("#.#");
        double parse = Double.parseDouble(df.format(x1));
        return parse;
    }

    private String rightRate(Double x1) {
        if (x1 == null) { return "0%"; }
        String rightRate = this.getDouble(x1).toString().concat("%");
        return rightRate.replace(".0%", "%");
    }
}
